/**
 * @author:linjiye
 * @date: 2024/12/25
 * @desc:
 **/

import {StyleSheet, Text, TextInput, TouchableOpacity, View} from 'react-native'
import React, {useEffect, useState} from 'react'
import PageScrollView from "@/components/PageScrollView";
import {Provider, Toast} from "@ant-design/react-native";
import PageSearch from "@/components/PageSearch";
import KeywordHighlighter from "@/components/KeywordHighlighter";
import NoData from "@/components/NoData";
import {useDispatch, useSelector} from "react-redux";
import Loading from "@/components/Loading";
import useGetStorage from "@/hooks/useGetStorage";
import {router} from "expo-router";

type Props = {}

const _layout = (props: Props) => {

    const dispatch = useDispatch();
    let p = useSelector(state => state.aiFeeding.pageRouterParams)

    const [pageScrollBodyH, setPageScrollBodyH] = useState(0)
    const [list, setList] = useState([])
    const [loading, setLoading] = useState(false)
    const [requestPath, setRequestPath] = useState('')
    const [params, setParams] = useState({})
    const [keyword, setKeyword] = useState('')

    useEffect(() => {
        if(p?.pageName) {
            console.log(p);
            switch (p?.pageName) {
                case 'aiFeeding':
                    setRequestPath('mm/mmVpGroup/itemList')
                    let params = {
                        // types: p?.params?.typeId || '',
                        // parentId: p?.params?.groupData?.id || '',
                        types:  '',
                        parentId:  '',
                        name: ''
                    }
                    setParams(params)
                    break;
                case 'keywordExplosion':
                case 'benchmarkingAccount':
                    setRequestPath('mm/mmObserveVideo/list')
                    setParams(p?.params)
                    break;
                case 'productDetail':
                    setRequestPath('')
                    break;
            }
        }
    },[p])

    function getScrollBodyInfo({height}) {
        setPageScrollBodyH(height)
    }

    function takeSearch(val) {
        setKeyword(val)
        setLoading(true)
        setList([])
        getData(val)
    }

    async function getData(key){
        console.log(requestPath,'----',params);
        await useGetStorage('token').then(async (token) => {
            try {
                // 将参数对象转换为查询字符串
                let p = {
                    ...params,
                    name: key
                }

                // 将参数对象转换为查询字符串
                const queryString = Object.keys(p)
                    .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(p[key]))
                    .join('&');

                const response = await fetch(`${process.env.EXPO_PUBLIC_API_URL}${requestPath}?${queryString}`,{
                    method: 'get',
                    headers: {
                        'content-type': 'application/json',
                        'x-access-token': token,
                    },
                })
                let data = await response.json()
                console.log(data);
                setLoading(false)
                let {code,message,result} = data
                if (code === 200) {
                    let list = result?.records || result
                    setList(list || [])
                } else {
                    Toast.info(message)
                }
            } catch (e) {
                console.log(e);
                setLoading(false)
            }
        })
    }

    function handleSelect(item: any) {
        switch (p?.pageName) {
            case 'aiFeeding':
                router.push('/aiFeeding/details?id='+item.id)
                break;
        }
    }

    return (
        <PageScrollView
            isTransparentTab
            getPageScrollBodyInfo={getScrollBodyInfo}
            pageTab={
                <PageSearch style={{marginVertical: 10}} onSearch={takeSearch}/>
            }
        >
            {loading &&
                <View style={{width: '100%',height:pageScrollBodyH - 150}}>
                    <Loading style={{backgroundColor: 'transparent',width: '100%',height:'100%'}}/>
               </View>
            }
            {list?.length <= 0 && !loading &&
                <View style={{height: pageScrollBodyH - 150}}>
                    <NoData hintText='暂无数据，输入相关关键字搜索您想要的内容吧~~'/>
                </View>
            }
            {list?.length > 0 && !loading &&
                list?.map((item, index) =>
                    <View style={{paddingVertical: 2}} key={index}>
                        <TouchableOpacity onPress={() => handleSelect(item)}>
                            <View style={styles.search_item_wrap}>
                                <KeywordHighlighter
                                    text={item.name || item.title}
                                    keywords={keyword}
                                    textStyle={styles.search_text}
                                    textHeightLightStyle={{color: '#2856FF'}}
                                />
                                <Text>({item.count})</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                )
            }
        </PageScrollView>
    )
}

export default _layout

const styles = StyleSheet.create({
    search_item_wrap: {
        flexDirection: 'row',
        minHeight: 56,
        display: 'flex',
        alignItems: "center",
        borderBottomWidth: 1,
        borderBottomColor: 'rgba(0,0,0,0.1)',
    },
    search_text: {
        color: 'rgba(0, 0, 0, 0.9)'
    }
})